package com.sum.tea.rongrui

import android.app.AlertDialog
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.*
import androidx.lifecycle.Observer
import com.example.lib_rongrui.FileImport
import com.sum.common.base.BaseMvvmActivity
import com.sum.tea.R
import com.sum.tea.contants.AppConstants
import com.sum.tea.databinding.QueryBinding
import com.sum.tea.rongrui.viewmodel.ScanModeViewModel

class ScanModeActivity : BaseMvvmActivity<QueryBinding, ScanModeViewModel>(), View.OnClickListener, AdapterView.OnItemClickListener {

    private lateinit var binding: QueryBinding
    private lateinit var viewModel: ScanModeViewModel

    private lateinit var adapter: SimpleAdapter
    private var items: Array<String>? = null
    private var chk: BooleanArray? = null
    private var ledList: MutableList<String> = mutableListOf()

    override fun initView(savedInstanceState: Bundle?) {
        binding = mBinding
        viewModel = mViewModel
        window.setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)

        setupUI()
        setupObservers()
    }

    private fun setupUI() {
        binding.chkLed.setOnClickListener(this)
        binding.layoutled.visibility = View.GONE

        // Setup Spinner
        ArrayAdapter.createFromResource(
            this,
            R.array.arrayfactory,
            android.R.layout.simple_spinner_item
        ).also { adapter ->
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            binding.spfactory.adapter = adapter
        }
        binding.spfactory.setSelection(0, false)

        // Initialize tag list and adapter
        adapter = SimpleAdapter(
            this,
            mutableListOf<HashMap<String, String>>(),
            R.layout.listtag_items,
            arrayOf("tagUii", "tagLen", "tagCount", "tagRssi"),
            intArrayOf(R.id.TvTagUii, R.id.TvTagLen, R.id.TvTagCount, R.id.TvTagRssi)
        )
        binding.LvTags.adapter = adapter
        binding.LvTags.setOnCreateContextMenuListener(lvContextMenuListener)
        binding.LvTags.onItemClickListener = this

        // Set click listeners
        binding.BtClear.setOnClickListener(this)
        binding.Btfilter.setOnClickListener(this)
        binding.BtImport.setOnClickListener(this)
        binding.BtInventory.setOnClickListener(this)

        // Setup RadioGroup listener
        binding.RgInventory.setOnCheckedChangeListener { group, checkedId ->
            viewModel.inventoryFlag = when (checkedId) {
                R.id.RbInventorySingle -> 0
                R.id.RbInventoryLoop -> 1
                else -> 1
            }
        }

        viewModel.clearData()
        Log.i("MY", "UHFReadTagFragment.EtCountOfTags=${viewModel.count.value}")
    }

    private fun setupObservers() {
        viewModel.tagList.observe(this) { tags ->
            adapter = SimpleAdapter(this, tags,
                R.layout.listtag_items,
                arrayOf("tagUii", "tagLen", "tagCount", "tagRssi"),
                intArrayOf(R.id.TvTagUii, R.id.TvTagLen, R.id.TvTagCount, R.id.TvTagRssi)
            )
            binding.LvTags.adapter = adapter
            binding.tvCount.text = viewModel.count.value
        }

        viewModel.count.observe(this, Observer { count ->
            binding.tvCount.text = count
        })

        viewModel.time.observe(this, Observer { time ->
            binding.tvTimes.text = time
        })

        viewModel.allTag.observe(this, Observer { allTag ->
            binding.tvAlltag.text = allTag
        })

        viewModel.speed.observe(this, Observer { speed ->
            binding.tvTagspeed.text = speed
        })

        viewModel.isInventorying.observe(this, Observer { isInventorying ->
            if (isInventorying) {
                binding.BtInventory.text = getString(R.string.title_stop_Inventory)
                setViewEnabled(false)
            } else {
                binding.BtInventory.text = getString(R.string.btInventory)
                setViewEnabled(true)
            }
        })
    }

    private fun setViewEnabled(enabled: Boolean) {
        binding.RbInventorySingle.isEnabled = enabled
        binding.RbInventoryLoop.isEnabled = enabled
        binding.BtClear.isEnabled = enabled
        binding.chkLed.isEnabled = enabled
        binding.Btfilter.isEnabled = enabled
        binding.BtInventory.isEnabled = enabled
    }

    override fun onClick(view: View?) {
        when (view) {
            binding.BtInventory -> readTag()
            binding.BtClear -> viewModel.clearData()
            binding.chkLed -> {
                binding.layoutled.visibility = if (binding.chkLed.isChecked) View.VISIBLE else View.GONE
            }
            binding.Btfilter -> showFilterDialog()
            binding.BtImport -> importData()
        }
    }

    private fun readTag() {
        if (binding.BtInventory.text == getString(R.string.btInventory)) {
            viewModel.startInventory(
                viewModel.inventoryFlag,
                ledList.takeIf { it.isNotEmpty() },
                binding.spfactory.selectedItemPosition
            )
        } else {
            viewModel.stopInventory()
        }
    }

    private fun showFilterDialog() {
        if (viewModel.tagList.value.isNullOrEmpty()) {
            Toast.makeText(this, getString(R.string.msgNodata), Toast.LENGTH_SHORT).show()
            return
        }
        items = viewModel.tagList.value?.map { it["tagUii"] ?: "" }?.toTypedArray()
        chk = BooleanArray(items?.size ?: 0)

        AlertDialog.Builder(this).apply {
            setTitle(getString(R.string.strselecttag))
            setMultiChoiceItems(items, chk) { dialog, which, isChecked ->
                val selectedEpc = items?.get(which) ?: return@setMultiChoiceItems
                if (isChecked) {
                    if (!ledList.contains(selectedEpc)) ledList.add(selectedEpc)
                } else {
                    ledList.remove(selectedEpc)
                }
                chk?.set(which, isChecked)
            }
            setPositiveButton(getString(R.string.strok), null)
            setNegativeButton(getString(R.string.strcancle), null)
            create()
            show()
        }
    }

    private fun importData() {
        if (viewModel.tagList.value.isNullOrEmpty()) {
            Toast.makeText(this, getString(R.string.msgNodata), Toast.LENGTH_SHORT).show()
            return
        }
        val success = FileImport.daochu("", viewModel.tagList.value!!.toList())
        if (success) {
            Toast.makeText(this, getString(R.string.msgImportsuc), Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this, getString(R.string.msgImportfailed), Toast.LENGTH_SHORT).show()
        }
    }

    // Context Menu
    private val lvContextMenuListener = View.OnCreateContextMenuListener { menu, v, menuInfo ->
        menu.setHeaderTitle(getString(R.string.strtagoperate))
        menu.add(0, 1, 0, getString(R.string.strreadandwrite))
        menu.add(0, 2, 1, getString(R.string.strfindtag))
    }

    override fun onContextItemSelected(item: MenuItem): Boolean {
        val info = item.menuInfo as AdapterView.AdapterContextMenuInfo
        val position = info.position
        val epc = viewModel.tagList.value?.get(position)?.get("tagUii") ?: ""
        when (item.itemId) {
            1 -> AppConstants.TabState.postValue(2)
            2 -> AppConstants.TabState.postValue(1)
            else -> return super.onContextItemSelected(item)
        }
        return true
    }

    override fun onResume() {
        super.onResume()
        viewModel.isStopThread = false
    }

    override fun onPause() {
        super.onPause()
        viewModel.stopInventory()
    }

    override fun onDestroy() {
        super.onDestroy()
        // Clean up if necessary
    }

    override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
        // Handle item click if necessary
    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == 523 && !viewModel.keyPress) {
            viewModel.keyPress = true
            readTag()
            return true
        } else if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == 523) {
            viewModel.keyPress = false
        }
        return super.onKeyUp(keyCode, event)
    }

    companion object {
        var epc: String = ""
    }
}
